package tp.pr3.instructions;

import tp.pr3.Message;
import tp.pr3.NavigationModule;
import tp.pr3.RobotEngine;
import tp.pr3.instructions.exceptions.InstructionExecutionException;
import tp.pr3.instructions.exceptions.WrongInstructionFormatException;
import tp.pr3.items.Item;
import tp.pr3.items.ItemContainer;

public class PickInstruction implements Instruction {

	public PickInstruction() {
		s = "";
	}

	public PickInstruction(String cad) {
		s = cad;
	}

	@Override
	public Instruction parse(String cad) throws WrongInstructionFormatException {
		String[] words = cad.split(" ");
		if (words.length != 2)
			throw new WrongInstructionFormatException(Message.NOT_UNDERSTAND);
		for (String i : Message.PICK_INSTRUCTION) {
			if (words[0].equalsIgnoreCase(i))
				return new PickInstruction(words[1]);
		}
		throw new WrongInstructionFormatException(Message.NOT_UNDERSTAND);
	}

	@Override
	public String getHelp() {
		String help = Message.PICK_INSTRUCTION[0];
		for (int i = 1; i < Message.PICK_INSTRUCTION.length; i++)
			help += "|" + Message.PICK_INSTRUCTION[i];
		help += " <id>";
		return help;
	}

	@Override
	public void configureContext(RobotEngine engine,
			NavigationModule navigation, ItemContainer robotContainer) {
		this.navigation = navigation;
		this.robotContainer = robotContainer;

	}

	@Override
	public void execute() throws InstructionExecutionException {
		Item it = this.navigation.pickItemFromCurrentPlace(this.s);
		if (it == null)
			throw new InstructionExecutionException(
					Message.NO_ITEM_IN_PLACE.replace("<id>", this.s));
		else {
			if (this.robotContainer.getItem(this.s) != null) {
				this.navigation.dropItemAtCurrentPlace(it);
				throw new InstructionExecutionException(
						Message.ITEM_REPEATED.replace("<id>", it.getId()));
			} else {
				this.robotContainer.addItem(it);
				System.out.println(Message.ITEM_ADDED.replace("<id>",
						it.getId()));
			}
		}

	}

	private NavigationModule navigation;
	private ItemContainer robotContainer;
	private RobotEngine engine;
	private String s;// instrucción
}
